﻿#region

using MediaSage.Lib.Utilities;
using NHibernate;

#endregion

namespace MediaSage.Lib.Database
{
    public abstract class DatabaseObject
    {
        #region Constructors

        protected static ConfigEntity config = null;

        private object lockObect = new object();

        protected DatabaseObject()
        {
            if (DBUtil.GetSession() != null && !DBUtil.GetSession().IsOpen)
            {
                DBUtil.GetSession();
            }
            if (DBUtil.GetSession() != null && config == null)
            {
                config = (ConfigEntity)DBUtil.GetSessionFactory().OpenSession().CreateCriteria(typeof(ConfigEntity)).UniqueResult();
            }
        }

        #endregion Constructors

        #region Methods

        public virtual void Delete()
        {
            lock (lockObect)
            {
                ISession session = DBUtil.GetSession();
                ITransaction tranaction = session.BeginTransaction();
                session.Delete(this);
            }
        }

        public virtual void Save()
        {
            lock (lockObect)
            {
                ISession session = DBUtil.GetSession();
                ITransaction tranaction = session.BeginTransaction();
                session.Save(this);
                tranaction.Commit();
            }
        }

        public virtual void SaveOrUpdate()
        {
            lock (lockObect)
            {
                ISession session = DBUtil.GetSession();
                ITransaction tranaction = session.BeginTransaction();
                session.SaveOrUpdate(this);
                tranaction.Commit();
            }
        }

        #endregion Methods
    }
}